Conditionally displayed fields
Let's further improve
the group of fields that ask visitors how they would like to be
contacted. Since the text inputs need to be entered only if their
corresponding checkboxes are checked, we can hide them, along with
their corresponding flags, when the document is initially loaded:
$(document).ready(function() {
$('input.conditional').next('span').andSelf().hide();
});
The fieldset now has its streamlined interface:
To make the text inputs and flags appear, we attach the .click()
method to each checkbox. We'll do so within the context of each
conditional text input so that we can set a couple of variables for
reuse:
$(document).ready(function() {
$('input.conditional').next('span').andSelf().hide()
.end().end()
.each(function() {
var $thisInput = $(this);
var $thisFlag = $thisInput.next('span');
$thisInput.prev('label').find(':checkbox')
.click(function() {
// code continues . . .
});
});
});
Here again we make use of two .end() methods, this time so we can attach the .each() method to the original $('input.conditional') selector.
Now we have a variable for
the current text input and the current flag. When the user clicks the
checkbox, we see if it is checked; if it is, we show the text input,
show the flag, and add the req-label class to the parent<label> element:
$(document).ready(function() {
$('input.conditional').next('span').andSelf().hide()
.end().end()
.each(function() {
var $thisInput = $(this);
var $thisFlag = $thisInput.next('span');
$thisInput.prev('label').find(':checkbox')
.click(function() {
if (this.checked) {
$thisInput.show();
$thisFlag.show();
$(this).parent('label').addClass('req-label');
}
});
});
});
For testing whether a box is checked here, this.checked is preferred because we have direct access to the DOM node via the this keyword. When the DOM node is not so accessible, we can use $('selector').is(':checked') instead, since .is() returns a Boolean (true or false).
We're left with two more things to do:
1.
Ensure that the checkboxes are unchecked when the page initially loads,
since some browsers will retain the state of form elements on page
refresh.
2. Add an else condition that hides the conditional elements and removes the req-label class when the checkbox is not checked.
$(document).ready(function() {
$('input.conditional').next('span').andSelf().hide()
.end().end()
.each(function() {
var $thisInput = $(this);
var $thisFlag = $thisInput.next('span');
$thisInput.prev('label').find(':checkbox')
.attr('checked', false)
.click(function() {
if (this.checked) {
$thisInput.show();
$thisFlag.show();
$(this).parent('label').addClass('req-label');
} else {
$thisInput.hide();
$thisFlag.hide();
$(this).parent('label')
.removeClass('req-label');
}
});
});
And that concludes the styling portion of this form makeover. Next, we'll add some client-side validation.